<?php

	// +----------------------------------------------------------------------
	// | 文档控制器
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\cms\admin;

	use app\model\cms\Document as DocumentModel;
	use app\model\cms\Category as CategoryModel;
	use app\event\cms\Document as DocumentEvent;
	use app\event\cms\Category as CategoryEvent;
	use app\event\cms\Attribute as AttributeEvent;
	use app\model\cms\Pattern as PatternModel;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;
	use app\controller\admin\Common;
	use think\facade\Url;

	class Document extends Common
	{

		protected function initialize()
		{
			parent::initialize();
			$this->dbname = 'Document';
			$this->model = new DocumentModel();
		}

		/**
		 * 分类文档列表页
		 * @return string
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function index()
		{
			$category_id = $this->request->param('cid');
			$category = CategoryModel::where('status', 1)->where('id', $category_id)->find();
			// 读取规则列表
			//            $map[] = ['pattern_id', '=', $pattern['id']];
			$map[] = ['category_id', 'in', CategoryEvent::getIdsWithChild($category_id)];
			$map[] = ['status', '>', -2];
			// 显示页面
			$builder = new Table();
			$builder->model(DocumentModel::class)
				->where($map)
				->order('id DESC')
				->searchTextLike('title', '搜索标题：', '标题');
			foreach ($category->patterns()->select() as $item) {
				$builder->buttonFull('cms/admin/Document/update?pattern_id=' . $item->id . '&category_id=' . $category['id'], '新增' . $item['title'], [
					'data-icon' => $item['icon'],
					'data-max' => 'true'
				]);
			}
			$builder->keyId()
//				->keyImageModel('cover_id', '封面')
				->keyImageModel('cover_id', '封面')
				->keyTitle()
				->keyText('category.title', '分类栏目', false, 200)
				->keyText('useful', '有用', true, 100)
				->keyText('useless', '无用', true, 100)
				->keyText('view', '浏览量', true, 100)
				->keyUser('user_id', '发布人')
				->keyCreateTime()
				->keyStatus()
				->actionUpdate()
				->actionDelete()
				//                ->actionToCheck('check?id={$id}','审核',[0])
//				->actionForbid()
				->actionRestore();
			return $builder->fetch();
		}


		public function checks()
		{
			// 批量通过
			$result = DocumentModel::where('id', 'in', $this->request->param('id'))->update(['status' => 1]);
			if ($result > 0) {
				$this->_returnSuccess('批量通过审核' . $result . '个');
			} else {
				$this->_returnError('批量通过审核失败');
			}
		}

		/**
		 * 文档更新页面初始化.
		 */
		public function update()
		{
			if ($this->request->isPost()) {
				// 验证数据
				$result = $this->validate($this->request->post(), \app\cms\validate\Document::class);
				if (true === $result) {
					$event = new DocumentEvent();
					$result = $event->update($this->request->post(), $this->user);
					if (0 == $result['code']) {
						$this->_returnSuccess($result['message'], true);
					} else {
						$this->_returnError($result['message']);
					}
				} else {
					$this->_returnError($result);
				}
			} else {
				if ($this->request->has('id', 'get')) {
					$event = new DocumentEvent();
					$result = $event->detail($this->request->param(), $this->user);
					if (0 == $result['code']) {
						$data = $result['data'];
					} else {
						$this->_returnError($result['message']);
					}
					$pattern = $data['pattern'];
				} else {
					if (!$this->request->has('pattern_id', 'get')) {
						$this->_returnError('未选择要操作的模型');
					} else {
						// 创建的默认值
						$data['pid'] = $this->request->has('pid', 'get') ? $this->request->get('pid') : 0;
						$data['pattern_id'] = $this->request->get('pattern_id');
						$data['category_id'] = $this->request->get('category_id');
						$pattern = PatternModel::find($data['pattern_id']);
					}
				}
				$allow = CategoryEvent::isAllow($data);
				// 检查分类是否存在
				if (true !== $allow) {
					$this->_returnError($allow);
				}
				// 获取表单字段
				$builder = new Edit();
				$builder->title($this->request->has('id', 'get') ? ('编辑' . $pattern['title']) : ('新增' . $pattern['title']));
				$builder->keyHidden('pattern_id')
					->keyText('title', '标题')
					->keySelect('category_id', '所属分类', CategoryEvent::getAllow($data))
					->keyImageModel('cover_id', '封面')
//					->keyImageModelMultiple('images','图库')
					->keyEditor($pattern['name'] . '.content', '内容')
					->keyTextArea('keywords', '关键词')
					->keyTextArea('description', '描述')
					// 批量设置触发器
					// $builder->setTrigger();
					// 设置分组
					//            $builder->group(ModelModel::getModelBuilderGroup($data['pattern_id']));
					->data($data)
					->buttonSubmit();
				return $builder->fetch();
			}
		}

		/**
		 * 删除消息
		 */
		public function delete()
		{
			$message = DocumentModel::where('id', $this->request->param('id'))->find();
			if ($message) {
				$message['status'] = -2;
				$message->save();
				$this->_returnSuccess( '删除成功');
			} else {
				$this->_returnSuccess( '操作失败');
			}
		}

		/**
		 * 文档更新页面初始化.
		 */
		//        public function update()
		//        {
		//            if ( $this->request->isPost() ) {
		//                $data = $this->model->find($this->request->param('id',0));
		//                if ($data)
		//                {
		//                    $data['title'] = $this->request->post('title');
		//                    $data['view'] = $this->request->post('view');
		//                    if ($data->save())
		//                    {
		//                        $this->_returnSuccess( '更新成功',true);
		//                    }else{
		//                        $this->_returnError( '更新失败');
		//                    }
		//                }else{
		//                    $this->_returnError( '文档不存在，或者已经删除');
		//                }
		//            } else {
		//                    // 获取详细数据
		//                    $data = $this->model->find($this->request->get('id',0));
		//                    if ( !$data) {
		//                        $this->_returnError( '文档不存在，或者已经删除');
		//                    }
		//
		//                $builder = new Edit();
		//                $builder->title('编辑文档');
		//                $builder->keyText('title','标题','',50)
		//                    ->keyNumber('view','阅读量')
		//                    ->keyNumber('share_coin','分享得绣币')
		//                    ->keyNumber('all_coin','已经获取绣币')
		//                ;
		//                $builder->data($data)
		//                    ->buttonSubmit('', '保存')
		//                    ->buttonClose();
		//                return $builder->fetch();
		//            }
		//        }
	}
